package com.ophiux.gateway.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.nacos.api.model.v2.Result;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @desc:
 * @author: hhl
 * @date：2021/10/22 11:44
 */
@RestController
public class TestController {
    @Value("${spring.profiles.active}")
    String name;
    public static int coun = 0;

    @GetMapping
    public String index(){
        return "测试网关成功"+name;
    }

    @GetMapping("/testSlowRequest")
    @ApiOperation("熔断降级测试 -- 慢调用比例")
    @SentinelResource(value = "testSentinelSlowRequest", fallback = "fallback")
    public Result testSlowRequest() {
        try {
            coun = coun + 1;
            Thread.sleep(300);
        } catch (Exception e) {

        }
        return Result.success("成功" + coun);
    }

    @GetMapping("/testExceptionRatio")
    @ApiOperation("熔断降级测试 -- 异常占比")
    @SentinelResource(value = "testSentinelExceptionRatio", fallback = "fallback2")
    public Result testExceptionRatio() {
        coun = coun + 1;
        if (coun % 4 == 0) {
            int i = 1 / 0;
        }
        return Result.success("成功" + coun);
    }

    @GetMapping("/testExceptionCount")
    @ApiOperation("熔断降级测试 -- 异常数")
    @SentinelResource(value = "testSentinelExceptionCount", fallback = "fallback3")
    public Result testExceptionCount() {
        coun = coun + 1;
        if (coun % 3 == 0) {
            int i = 1 / 0;
        }
        return Result.success("成功" + coun);
    }


    @GetMapping("/test2")
    @ApiOperation("流量控制测试")
    public Result test2() {
        coun = coun + 1;
        return Result.success("成功" + coun);
    }

    public Result fallback() {
        return Result.failure("服务降级啦，当前服务器请求过慢，请稍后重试!");
    }

    public Result fallback2() {
        return Result.failure("服务降级啦，当前服务器请求异常占比过多，请稍后重试!");
    }

    public Result fallback3() {
        return Result.failure("服务降级啦，当前服务器请求异常数过多，请稍后重试!");
    }

    public Result fallback4() {
        return Result.failure("服务限流啦，当前服务器请求次数过多，请稍后重试!");
    }
}
